using System;
using System.Collections.Generic;
using System.Text;
using Dominio;
using NHibernate;
using NHibernate.Cfg;

namespace DAP
{
    public class ReleaseRepository : AbstractRepository
    {
        public ReleaseRepository()
            : base()
        {

        }

        public IList<Release> getReleaseList()
        {
            ISession sesion = sesiones.OpenSession();
            ITransaction transaction = sesion.BeginTransaction();
            IQuery query = sesion.CreateQuery("from Release");
            transaction.Commit();
            return query.List<Release>();
        }

        public Release getReleaseById(int Id)
        {
            ISession sesion = sesiones.OpenSession();
            ITransaction transaction = sesion.BeginTransaction();
            try
            {
                IQuery query = sesion.CreateQuery("from Release where Id = :x");
                query.SetString("x", Id.ToString());
                transaction.Commit();
                return (Release)query.UniqueResult();
            }
            catch
            {
                transaction.Rollback();
                throw new HibernateException();
            }
        }

        public void SaveRelease(Release release)
        {
            ISession sesion = sesiones.OpenSession();
            ITransaction transaction = sesion.BeginTransaction();
            try
            {
                sesion.SaveOrUpdate("Release", release);
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
                throw new HibernateException();
            }
        }

        public IList<Release> getFilteredReleaseList(String from, String to, String state, String key)
        {
            ISession sesion = sesiones.OpenSession();
            ITransaction transaction = sesion.BeginTransaction();
            try
            {
                String queryString = "from Release Release where Release.Description like '%" + key + "%'";
                if (!state.Equals("All"))
                {
                    queryString = queryString + " and Release.State = '" + state + "'";
                }
                if (!from.Trim().Equals("") && !to.Trim().Equals(""))
                {
                    queryString = queryString + " and Release.CreationDate between '" + from + "' and '" + to + "'";
                }
                IQuery query = sesion.CreateQuery(queryString);
                transaction.Commit();
                return query.List<Release>();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw new HibernateException();
            }
        }
    }
}
